﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using Reconciliation.Domain;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using System.Data;

namespace Reconciliation.Data
{
    public partial class User
    {
        public static Domain.User MapDataToDomain(Data.User dataUser)
        {
            Domain.User domainUser = new Reconciliation.Domain.User();
            domainUser.City = dataUser.City;
            domainUser.Email = dataUser.Email;
            domainUser.FamilyName = dataUser.FamilyName;
            domainUser.GivenName = dataUser.GivenName;
            domainUser.Password = dataUser.Password;
            domainUser.PostCode = dataUser.PostCode;
            if(dataUser.Role != null)
                domainUser.Role = Data.Role.MapDataToDomain(dataUser.Role);
            if(dataUser.State != null)
                domainUser.State = Data.State.MapDataToDomain(dataUser.State);
            domainUser.Street = dataUser.Street;
            domainUser.Telephone = dataUser.Telephone;
            domainUser.UserID = dataUser.UserID;
            domainUser.UserName = dataUser.UserName;

            return domainUser;
        }

        public static Domain.User GetUserByUserNameAndPassword(string userName, string password)
        {
            try
            {
                Domain.User domainUser = new Reconciliation.Domain.User();
                ReconciliationEntities reconEnt = new ReconciliationEntities();
                Data.User user = (from u in reconEnt.User.Include("Role").Include("Role.Permission")
                                  where u.UserName.ToUpper().Equals(userName.ToUpper()) && u.Password.Equals(password)
                                  select u).FirstOrDefault();
                if (user != null)
                    domainUser = MapDataToDomain(user);
                return domainUser;
            }
            catch (EntityException ex)
            {
                ExceptionPolicy.HandleException(ex, "Exception Policy");
                throw new ReconciliationException("Database exception occured please try again later.");
            }
            catch (Exception ex)
            {
                ExceptionPolicy.HandleException(ex, "Exception Policy");
                throw new ReconciliationException("User does not exists");
            }
        }
    }
}
